<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Log;

class AuthController extends Controller
{

    public function login(Request $request)
    {
        // Validate the request data
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        // Retrieve the user based on the email
        $user = User::where('email', $request->email)->first();

        // Check if the user exists and the password is correct
        if (!$user || !Hash::check($request->password, $user->password)) {
            return $this->_returnError(self::CODE_ERROR_AUTH_FAILED, 'The provided credentials are incorrect.');
        }

        // Generate a new auth token for the user
        $token = $user->createToken('authToken')->plainTextToken;

        // Return the auth token as a response
        return $this->_returnSuccess(['token' => $token], 'Login success');
    }

    public function logout(Request $request)
    {
        // Get the authenticated user
        /**
         * @var User $user
         */
        $user = $request->user();

        // Revoke the user's current token
        $succ=$user->currentAccessToken()->delete();
        Log::debug("logout: $succ");

        // Return a success response
        return $this->_returnSuccess(null, 'Logged out');
    }

}
